import create, {StateCreator} from 'zustand';
import {devtools, persist} from 'zustand/middleware';
import {zustandStorage} from './index';

export interface UserState {
  /** 用户信息 */
  userInfo: {
    /** 用户名 */
    sub?: string;
    /** 用户类型 */
    userType?: string;
    /** 用户名称 */
    realName?: string;
    /** 手机号 */
    phone?: string;
    /** 手机号 */
    password?: string;
    /** 邮箱 */
    email?: string;
    /** 部门 */
    deptName?: string;
    /** 租户id */
    tenantId?: number;
    /** 用户权限 */
    permissions?: any[];
    /** 用户id */
    id?: number;
  };
  /** 登录信息 */
  loginInfo: {
    /** 手机号 */
    phone?: string;
    /** 租户列表 */
    tenantList?: any;
    /** 验证码 */
    code?: string;
    /** 租户标识 */
    corUrl?: string;
  };
  setLoginInfo: (h: UserState['loginInfo']) => void;
  setUserInfo: (h: UserState['userInfo']) => void;
  setAccessToken: (h: string) => void;
  /** 用户权限 */
  permissions: any[];
  resources: any;
  setResources: (h: any) => void;
  /** 用户token */
  accessToken: string;
}

export const name = 'user-store';

const baseStateCreator: StateCreator<UserState> = set => ({
  userInfo: {},
  setUserInfo: (h: UserState['userInfo']) => {
    set({
      userInfo: h,
    });
  },
  loginInfo: {},
  setLoginInfo: (h: UserState['loginInfo']) => {
    set({
      loginInfo: h,
    });
  },
  resources: {},
  setResources: (h: any) => {
    set({
      resources: h,
    });
  },
  permissions: [],
  setPermissions: (h: any) => {
    set({
      permissions: h,
    });
  },
  accessToken: '-1',
  setAccessToken: (h: string) => {
    set({
      accessToken: h,
    });
  },
});

const useGlobalStore = create(
  devtools<UserState>(
    persist<UserState>(baseStateCreator, {
      name,
      getStorage: () => zustandStorage,
    }) as any,
  ),
);
export default useGlobalStore;
